<script setup>
import Device from '@/views/device/components/index.vue'
import Project from '@/views/device/components/project.vue'
import { computed } from 'vue'
// vue3方法实例
const { proxy } = getCurrentInstance()
// const { maintenance_project_level } = proxy.useDict('maintenance_project_level')

// 子传父
const emit = defineEmits()

// 父传子
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
  //   传入数据 用于回显
  data: {
    type: Object,
    default: () => {},
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  //   传入数据 弹窗标题
  title: {
    type: String,
    default: '新增',
  },
})

// 标签页字段
const activeName = ref('计划信息')

// 表单实例
const ruleFormRef = ref(null)

// 设备弹窗状态
const deviceShow = ref(false)

// 保养项目弹窗
const projectShow = ref(false)
// 周数据
const weekList = ref([
  {
    label: '周一',
    value: 1,
    key: 'week',
  },
  {
    label: '周二',
    value: 2,
    key: 'week',
  },
  {
    label: '周三',
    value: 3,
    key: 'week',
  },
  {
    label: '周四',
    value: 4,

    key: 'week',
  },
  {
    label: '周五',
    value: 5,
    key: 'week',
  },
  {
    label: '周六',
    value: 6,
    key: 'week',
  },
  {
    label: '周天',
    value: 7,
    key: 'week',
  },
])

// 月数据
const monthList = ref([
  {
    label: '一月',
    value: '01',
    key: 'month',
  },
  {
    label: '二月',
    value: '02',
    key: 'month',
  },
  {
    label: '三月',
    value: '03',
    key: 'month',
  },
  {
    label: '四月',
    value: '04',
    key: 'month',
  },
  {
    label: '五月',
    value: '05',
    key: 'month',
  },
  {
    label: '六月',
    value: '06',
    key: 'month',
  },
  {
    label: '七月',
    value: '07',
    key: 'month',
  },
  {
    label: '八月',
    value: '08',

    key: 'month',
  },
  {
    label: '九月',
    value: '09',

    key: 'month',
  },
  {
    label: '十月',
    value: '10',
    key: 'month',
  },
  {
    label: '十一月',
    value: '11',
    key: 'month',
  },
  {
    label: '十二月',
    value: '12',
    key: 'month',
  },
])

const columnData = ref([
  { label: '项目编号', prop: 'maintenanceProjectCode' },
  { label: '项目名称', prop: 'maintenanceProjectName' },
  { label: '项目类型', prop: 'projectType' },
  { label: '设备编码', prop: 'deviceCode' },
  { label: '设备名称', prop: 'deviceName' },

  { label: '保养部位', prop: 'maintenancePosition' },
  { label: '保养级别', prop: 'maintenanceLevelDict' },
  { label: '维保内容', prop: 'maintenanceContent' },
  { label: '备件或耗材型号', prop: 'consumables', width: '180px' },
  { label: '计划指令', prop: 'paleInstructStr' },
  { label: '维保数量', prop: 'maintenanceNum' },
  { label: '标准工时', prop: 'workingHour' },
  { label: '备注', prop: 'remark' },
])

const columnDataA = ref([
  { label: '设备名称', prop: 'deviceName' },
  { label: '设备编码', prop: 'deviceCode' },
  { label: '设备类型', prop: 'deviceType' },
  { label: '设备型号', prop: 'deviceUnitType' },
  { label: '设备位置', prop: 'installationLocation' },
  { label: '操作', prop: 'x' },
])

// 自定义验证
const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请填写计划配置项'))
  }
}
// 表单字段
const ruleForm = reactive({
  planName: '', // 计划名称
  planStartTime: '', // 开始时间
  planEndTime: '', // 结束时间
  maintenanceProjectIdStr: '', //保养项目id
  equipmentIdStr: '', //设备id
  status: '', //状态
  list: [],
  drvices: [],
  maintenanceProjects: [],
  plannedAllocation: {
    //
    planType: 1, //
    executionInterval: '', //
    executionCycle: [], //
    executionMonth: [], //
    executionDays: [], //
  },
})

// 表单校验
const rules = reactive({
  planName: [{ required: true, message: '请填写计划名称', trigger: 'blur' }],
  plannedAllocation: [
    { required: true, message: '请填写计划配置项', trigger: 'blur' },
    { validator: checkAge },
  ],
  planStartTime: [
    { required: true, message: '请选择计划开始时间', trigger: 'change' },
  ],
  planEndTime: [
    { required: true, message: '请选择计划结束时间', trigger: 'change' },
  ],
})

// 日期数据
const dayList = ref([])

// 生成日期数据
const initDay = () => {
  let i1
  for (let i = 0; i < 31; i++) {
    if (i < 9) {
      i1 = `0${i + 1}`
    } else {
      i1 = i + 1
    }
    dayList.value.push({
      label: i1,
      value: i,
      key: 'day',
    })
  }
}

initDay()

// 添加设备
const addDevice = (val) => {
  ruleForm.drvices = val
  deviceShow.value = false
}

// 添加保养项目
const addProject = (val) => {
  ruleForm.maintenanceProjects.push(...val)
  projectShow.value = false
}

// 删除设备
const removeDevice = (id) => {
  const findId = ruleForm.drvices.findIndex((item) => item.id === id)

  if (findId == -1) return console.error(new Error('未找到id'))
  ruleForm.drvices.splice(findId, 1)
}

// 提交方法
const submit = async () => {
  const valid = await ruleFormRef.value.validate()
  if (!valid) return false
  // 计划配置项 执行月份
  ruleForm.plannedAllocation.executionMonth = monthList.value
    .filter((item) => item.isShow)
    .map((item) => item.value)
    .join(',')
  // 计划配置项 执行周期
  ruleForm.plannedAllocation.executionCycle = weekList.value
    .filter((item) => item.isShow)
    .map((item) => item.value)
    .join(',')
  // 计划配置项 执行日期
  ruleForm.plannedAllocation.executionDays = dayList.value
    .filter((item) => item.isShow)
    .map((item) => item.value)
    .join(',')

  // 保养id
  ruleForm.maintenanceProjectIdStr = ruleForm.maintenanceProjects
    .map((item) => item.id)
    .join(',')

  // 执行间隔
  console.log(
    !ruleForm.plannedAllocation.executionInterval,
    ruleForm.plannedAllocation.executionInterval,
    'ruleForm.plannedAllocation.executionInterval'
  )

  if (
    ruleForm.plannedAllocation.planType != 3 &&
    !(ruleForm.plannedAllocation.executionInterval == 0
      ? true
      : ruleForm.plannedAllocation.executionInterval)
  ) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 周期
  if (
    ruleForm.plannedAllocation.planType == 2 &&
    !weekList.value.some((item) => item.isShow)
  ) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 月份
  if (
    ruleForm.plannedAllocation.planType == 3 &&
    !monthList.value.some((item) => item.isShow)
  ) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 执行间隔 日期
  if (
    ruleForm.plannedAllocation.planType == 3 &&
    !dayList.value.some((item) => item.isShow)
  ) {
    proxy.warningMsg('请完善计划配置项内容')
    return false
  }

  // 保养项目
  if (ruleForm.maintenanceProjects.length < 1) {
    proxy.warningMsg('请完善保养项目内容')
    return false
  }

  ruleForm.equipmentIdStr = ruleForm.drvices.map((item) => item.id).join(',')
  return ruleForm
}

const selectArr = ref([])
const handleSelectionChanges = (rows) => {
  selectArr.value = rows
}

const remove = () => {
  if (selectArr.value.length > 0) {
    selectArr.value.forEach((item) => {
      const Find = ruleForm.maintenanceProjects.findIndex(
        (itemy) => item.id == itemy.id
      )
      ruleForm.maintenanceProjects.splice(Find, 1)
    })
  } else {
    if (ruleForm.maintenanceProjects?.length < 1) return
    ruleForm.maintenanceProjects.splice(
      ruleForm.maintenanceProjects.length - 1,
      1
    )
  }
}

// 监听回显
const initData = () => {
  if (props.data?.id) {
    Object.keys(props.data).forEach(
      (itemKey) => (ruleForm[itemKey] = props.data[itemKey])
    )
    ruleForm.plannedAllocation = props.data.plannedAllocationDto

    const executionCycle = ruleForm.plannedAllocation.executionCycleList
    const executionMonthList = ruleForm.plannedAllocation.executionMonthList
    const executionDaysList = ruleForm.plannedAllocation.executionDaysList
    // 月份
    if (Array.isArray(executionMonthList) && executionMonthList.length > 0) {
      executionMonthList.forEach((itemy) => {
        monthList.value.forEach((item) => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 日期
    if (Array.isArray(executionDaysList) && executionDaysList.length > 0) {
      executionDaysList.forEach((itemy) => {
        dayList.value.forEach((item) => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 周期
    if (Array.isArray(executionCycle) && executionCycle.length > 0) {
      executionCycle.forEach((itemy) => {
        weekList.value.forEach((item) => {
          if (item.value == itemy) item.isShow = true
        })
      })
    }

    // 保养项目
  }
}

initData()

// 计算共和
const total = computed(() => {
  let total = 0
  if (
    Array.isArray(ruleForm.maintenanceProjects) &&
    ruleForm.maintenanceProjects?.length > 0
  ) {
    ruleForm.maintenanceProjects.forEach((item) => (total += item.workingHour))
  }
  return total
})
// 导出方法
defineExpose({ submit })
</script>
<template>
  <el-tabs
    v-model="activeName"
    type="card"
    class="demo-tabs"
    @tab-click="handleClick"
  >
    <el-tab-pane label="计划信息" name="计划信息">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="160px"
        status-icon
      >
        <el-form-item label="计划编号" v-if="props.title != '新增'">
          <el-input clearable v-model="ruleForm.maintenancePlanCode" disabled />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input
            clearable
            v-model="ruleForm.planName"
            :disabled="props.disabled"
            placeholder="请填写计划名称"
          />
        </el-form-item>
        <el-form-item label="项目开始时间" prop="planStartTime">
          <el-date-picker
            :disabled="props.disabled"
            v-model="ruleForm.planStartTime"
            type="date"
            placeholder="请选择项目开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="项目结束时间" prop="planEndTime">
          <el-date-picker
            :disabled="props.disabled"
            v-model="ruleForm.planEndTime"
            type="date"
            placeholder="请选择项目结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <div class="rk">
          <el-form-item label="计划配置项" prop="name">
            <div class="box">
              <div class="config">
                <label class="labelClass">计划类型:</label>
                <el-radio-group
                  :disabled="props.disabled"
                  v-model="ruleForm.plannedAllocation.planType"
                  class="option"
                >
                  <el-radio :label="4" size="large">小时</el-radio>
                  <el-radio :label="1" size="large">日</el-radio>
                  <el-radio :label="2" size="large">周</el-radio>
                  <el-radio :label="3" size="large">月</el-radio>
                </el-radio-group>
              </div>
              <!-- 小时 -->
              <div v-if="ruleForm.plannedAllocation.planType == 4">
                <label class="labelClass" style="margin-right: 20px"
                  >执行间隔:</label
                >
                <el-input
                  type="number"
                  clearable
                  min="0"
                  :disabled="props.disabled"
                  v-model="ruleForm.plannedAllocation.executionInterval"
                  style="width: 200px"
                  placeholder="单行输入"
                  oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<0||value==0){value=''} if(value>999999999){value=999999999}"
                />
                <span> &nbsp;&nbsp;H</span>
              </div>
              <!-- 天 -->
              <div class="day" v-if="ruleForm.plannedAllocation.planType == 1">
                <label class="labelClass">执行间隔:</label>
                <el-input
                  type="number"
                  clearable
                  min="0"
                  :disabled="props.disabled"
                  v-model="ruleForm.plannedAllocation.executionInterval"
                  placeholder="单行输入"
                  oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<0){value=''} if(value>999999999){value=999999999}"
                />
                <span> &nbsp;&nbsp;天</span>
              </div>
              <!-- 周 -->
              <div class="week" v-if="ruleForm.plannedAllocation.planType == 2">
                <div class="flex">
                  <label class="labelClass">执行间隔:</label>
                  <el-input
                    clearable
                    oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<0){value=''} if(value>999999999){value=999999999}"
                    :disabled="props.disabled"
                    type="number"
                    v-model="ruleForm.plannedAllocation.executionInterval"
                    placeholder="单行输入"
                    min="0"
                  />
                  <span>周</span>
                </div>
                <div class="flex">
                  <label class="labelClass">执行周期:</label>
                  <div class="wrap">
                    <el-checkbox
                      v-for="item in weekList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :key="item"
                      :label="item.label"
                    />
                  </div>
                </div>
              </div>
              <!-- 月 -->
              <div
                class="month"
                v-if="ruleForm.plannedAllocation.planType == 3"
              >
                <div class="flex">
                  <label class="labelClass">执行月份:</label>
                  <div class="wrap">
                    <el-checkbox
                      class="month-checkbox"
                      v-for="item in monthList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :key="item"
                      :label="item.label"
                    />
                  </div>
                </div>
                <div class="flex">
                  <label class="labelClass">执行日期:</label>
                  <div class="month-days wrap">
                    <el-checkbox
                      class="month-checkbox"
                      v-for="item in dayList"
                      :disabled="props.disabled"
                      v-model="item.isShow"
                      :key="item"
                      :label="item.label + '号'"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <p-table-add
        v-if="props.title != '查看'"
        title="保养项目"
        @add="projectShow = true"
        @remove="remove"
      />
      <p-table-form
        height="300"
        :isSel="false"
        keyId="id"
        className="tableClass"
        style="margin-top: 10px"
        :column="columnData"
        :data="ruleForm.maintenanceProjects"
      >
        <!-- <template #columnCell="{ column, record }"> -->
        <!-- <p-Text
            v-if="column.prop == 'maintenanceLevel'"
            :options="maintenance_project_level"
            :value="record.maintenanceLevel"
          /> -->
        <!-- </template> -->
      </p-table-form>
      <div class="total">
        总工时：
        {{ total }}
      </div>
    </el-tab-pane>
    <!-- <el-tab-pane label="关联设备" name="关联设备">
      <div class="caozuo" v-if="!props.disabled">
        <el-button class="mb10" @click="deviceShow = true"> 关联设备</el-button>
      </div>
      <p-table-form
        height="300"
        :isSel="false"
        keyId="id"
        className="tableClass"
        style="margin-top: 10px"
        :column="columnDataA"
        :data="ruleForm.drvices"
      >
        <template #columnCell="{ column, record }">
          <div v-if="column.prop == 'x'">
            <el-link
              type="primary"
              v-hasPermi="['device:maintenance:plan:edit']"
              text="解除关联"
              :disabled="props.title == '查看'"
              @click="removeDevice(record.id)"
            />
          </div>
        </template>
      </p-table-form>
    </el-tab-pane> -->
  </el-tabs>
  <!-- 保养项目 -->
  <Project
    :bdb="false"
    :is-show="projectShow"
    @preservation="addProject"
    :ids="ruleForm.maintenanceProjects.map((t) => t.id) || []"
    @cancel="projectShow = false"
  />
  <!-- 设备列表 -->
  <!-- <Device
    :bdb="false"
    :is-show="deviceShow"
    @preservation="addDevice"
    @cancel="deviceShow = false"
  /> -->
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}

.box {
  overflow: auto;
  & .labelClass {
    width: 120px !important;
  }
}
.config {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.day {
  display: flex;
  align-items: center;
}

.day ::v-deep .el-input {
  width: 150px !important;
}
.week ::v-deep .el-input {
  width: 150px !important;
}

.month ::v-deep .el-input {
  width: 150px !important;
}

.month-days {
  flex-wrap: wrap;
}
.month-checkbox {
  width: 50px;
}
.wrap {
  width: 100%;
  flex-wrap: wrap;
}

.caozuo {
  float: right;
  cursor: pointer;
}
.total {
  float: right;
  font-size: 16px;
  margin-top: 15px;
  margin-right: 15px;
}
</style>
